package it.antonio.ilpizze.te;


public class Lexer {
	
	
	
	private Reader reader;
	
	public Lexer(Reader reader) {
		this.reader = reader;
	}
	
	public Tokens tokens(){
		Tokens tokens = new Tokens();
		
		StringBuffer buffer = new StringBuffer();
		int position = -1;
		while (reader.hasNext()) {
			reader.next();
			
			position = reader.position(); 
			switch(reader.current()) {
			 	
			 	// SPECIALS
			 	case Token.CLOSE : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.OPEN : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.VALUE : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.OPERATION : { collect(buffer, position - 1, tokens);tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.INVERTED_OPERATION : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.POINT : { collect(buffer, position - 1, tokens);tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.TWO_POINTS : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.END_OPERATION : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.ESCAPE : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	case Token.FILTER : { collect(buffer, position - 1, tokens); tokens.add(Token.special(position, reader.current())); break;}
			 	
			 	// TEXT
			 	default:{
			 		buffer.append(reader.current());
			 	}
			 }
			 
		}
		collect(buffer, position, tokens); 
		return tokens;
	}
	
	
	
	private void collect(StringBuffer buffer, int position, Tokens tokens){
		if(buffer.length() > 0){
			String token = buffer.toString();
			tokens.add(Token.text(position - (token.length() - 1), token));
			buffer.setLength(0);
		}
	}

}
